package com.cisdi.analysis.service.impl;

import com.cisdi.analysis.common.util.StringUtil;
import com.cisdi.analysis.core.dto.AnalysisDataDTO;
import com.cisdi.analysis.repository.mapper.AnalysisDataMapper;
import com.cisdi.analysis.service.FileService;
import com.cisdi.analysis.service.util.ProcessorUtil;
import com.cisdi.analysis.service.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.*;
import org.supercsv.prefs.CsvPreference;

import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.supercsv.prefs.CsvPreference.STANDARD_PREFERENCE;

/**
 * 文件上传服务层
 * @author liujunnan
 * @date 2018/5/23
 */
@Service
public class FileServiceImpl implements FileService {

    @Value("${remote.data.path}")
    private String remoteDataPath;


    @Autowired
    private UploadFileUtil uploadFileUtil;

    @Autowired
    private AnalysisDataMapper analysisDataMapper;

    @Override
    public Map upload(MultipartFile files) throws Exception {


        //上传文件到云端和本地
        Map map = uploadFileUtil.uploadFile(files, remoteDataPath);
        String local = null;
        if (map != null) {
            if (map.get("local_file") == null || map.get("result") == null || map.get("original_name") == null) {
                throw new Exception("上传文件失败!");
            } else {
                local = map.get("local_file").toString();
            }
        }
        //用的superCsv导入
        //mapperReader导入map
        ICsvBeanReader beanReader = null;
        ArrayList list = new ArrayList(5000);
        try {
            beanReader = new CsvBeanReader(new FileReader(local), STANDARD_PREFERENCE);
            // the header columns are used as the keys to the Map
            beanReader.getHeader(true);
            final String[] header = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "quality"};
            final CellProcessor[] processors = ProcessorUtil.getProcessors();
            AnalysisDataDTO analysisDataDTO;
            while ((analysisDataDTO = beanReader.read(AnalysisDataDTO.class, header, processors)) != null) {
                list.add(analysisDataDTO);
                if (list.size() == 5000) {
                    analysisDataMapper.dataImport(list);
                    list = new ArrayList();
                }
            }
            analysisDataMapper.dataImport(list);
        } finally {
            if (beanReader != null) {
                beanReader.close();
            }
        }
        return map;
    }

    @Override
    public String deleteRow(Integer number, String localPath) throws Exception {
        ICsvBeanReader beanReader;
        ICsvBeanWriter beanWriter = null;
        try {
            List array = new ArrayList(50000);
            beanReader = new CsvBeanReader(new FileReader(localPath), STANDARD_PREFERENCE);
            String[] headerOld = beanReader.getHeader(true);
            final String[] header = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "quality"};
            final CellProcessor[] processors = ProcessorUtil.getProcessors();
            AnalysisDataDTO analysisDataDTO;
            while ((analysisDataDTO = beanReader.read(AnalysisDataDTO.class, header, processors)) != null) {
                array.add(analysisDataDTO);
            }
            //给定的行数超出范围
            if (number < 1 || number > array.size() + 1) {
                throw new Exception("超出范围！");
            }
            beanReader.close();
            beanWriter = new CsvBeanWriter(new FileWriter(localPath), CsvPreference.STANDARD_PREFERENCE);
            if (number == 1) {
                for (Object dataDTO1 : array) {
                    beanWriter.write(dataDTO1, header, processors);
                }
            } else {
                array.remove(number - 2);
                beanWriter.writeHeader(headerOld);
                for (Object dataDTO1 : array) {
                    beanWriter.write(dataDTO1, header, processors);
                }
            }
        } finally {
            if (beanWriter != null) {
                beanWriter.close();
            }
        }
        return null;
    }

    @Override
    public String deleteList(Integer number, String localPath) throws Exception {
        ICsvMapReader mapReader = null;
        ICsvMapWriter mapWriter = null;

        try {
            List<Map> arrays = new ArrayList<>(50000);
            mapReader = new CsvMapReader(new FileReader(localPath), CsvPreference.STANDARD_PREFERENCE);
            String[] headerOld = mapReader.getHeader(true);
            if (number < 1 || number > headerOld.length) {
                throw new Exception("超过列数!");
            }
            Map<String, Object> customerMap;
            final CellProcessor[] processors = ProcessorUtil.getProcessors();
            while ((customerMap = mapReader.read(headerOld, processors)) != null) {
                arrays.add(customerMap);
            }
            mapReader.close();
            String deleteChar = headerOld[number - 1];
            String[] headerNew = StringUtil.deleteByIndex(headerOld, number - 1);
            mapWriter = new CsvMapWriter(new FileWriter(localPath), CsvPreference.STANDARD_PREFERENCE);
            mapWriter.writeHeader(headerNew);
            for (Map array : arrays) {
                array.remove(deleteChar);
                mapWriter.write(array, headerNew);
            }
        } finally {
            if (mapWriter != null) {
                mapWriter.close();
            }
        }
        return null;
    }

    @Override
    public String updateRow(Integer number, String localPath, AnalysisDataDTO changeAnalysisDataDTO) throws Exception {
        ICsvBeanReader beanReader;
        ICsvBeanWriter beanWriter = null;
        try {
            List array = new ArrayList(50000);
            beanReader = new CsvBeanReader(new FileReader(localPath), STANDARD_PREFERENCE);
            String[] headerOld = beanReader.getHeader(true);
            //加头，和类的字段对应
            final String[] header = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "quality"};
            final CellProcessor[] processors = ProcessorUtil.getProcessors();
            AnalysisDataDTO analysisDataDTO;
            while ((analysisDataDTO = beanReader.read(AnalysisDataDTO.class, header, processors)) != null) {
                array.add(analysisDataDTO);
            }
            //给定的行数超出范围
            if (number < 1 || number == 1 || number > array.size() + 1) {
                throw new Exception("超出范围！");
            }
            beanReader.close();
            beanWriter = new CsvBeanWriter(new FileWriter(localPath), CsvPreference.STANDARD_PREFERENCE);
            array.set(number - 2, changeAnalysisDataDTO);
            beanWriter.writeHeader(headerOld);
            for (Object dataDTO1 : array) {
                beanWriter.write(dataDTO1, header, processors);
            }
        } finally {
            if (beanWriter != null) {
                beanWriter.close();
            }
        }
        return null;
    }
}
